package com.firmboy.lock;

import com.firmboy.threadPool.PoolFactory;
import org.junit.Test;
import sun.awt.windows.ThemeReader;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Synchronized对象锁的使用
 *
 * @author firmboy
 * @create 2018-05-04 下午7:29
 **/
public class SyncLock {


    class T {

        public synchronized void getA(){
            System.out.println("A执行");
            try {
                Thread.sleep(10L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public synchronized void relA(){
            System.out.println("A释放执行");
            try{
                Thread.sleep(10L);
            }catch(Exception e){
                e.printStackTrace();
            }

        }


    }


    class B implements Runnable{

        private  T t;
        private CyclicBarrier barrier;

        public B (T t,CyclicBarrier barrier){
            this.t = t;
            this.barrier = barrier;
        }

        @Override
        public void run() {
            t.getA();
            System.out.println(Thread.currentThread().getName()+"===============================");
            t.relA();
            try {
                barrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void test(){

        int count = 32;

        CyclicBarrier barrier = new CyclicBarrier(count-1);

        T t = new T();
        B b = new B(t,barrier);


        ThreadPoolExecutor pool = PoolFactory.getPool();



        for (int i =0;i<count;i++){
            pool.execute(b);
        }


        try {
            barrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}
